package Javaa.Base.Thread;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FutureEample {
    Callable<Long> task = () -> {
    Thread.sleep(3000); // 模拟耗时任务
    return System.currentTimeMillis();
};

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Long> future = executor.submit(task);
try {
    // 超时等待 2 秒，未完成则抛异常
    Long result = future.get(2, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    // 超时后取消任务
    future.cancel(true); // 中断正在执行的线程
    System.out.println("任务超时，已取消");
}

}
